﻿using AutoMapper;
using B.S.BaseData.Infrastructure.Interfaces;
using B.S.ProcessEgine.API.Applocations.Commands.FormTypeInfoCommand;
using B.S.ProcessEgine.API.Dtos.ResponseDto;
using B.S.ProcessEgine.Domain.Entities;
using B.S.ProcessEgine.ErrorCode;
using B.S.ProcessEgine.Infractructure.Interfaces;
using MediatR;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;

namespace B.S.ProcessEgine.API.Applocations.CommandHandlers.FormTypeInfoHandler
{
    public class PagingFormTypeInfoHandler : IRequestHandler<PagingFormTypeInfoCommand, ApiResult<ApiPaging<PagingFormTypeInfoRespDto>>>
    {
        IFormTypeRepository formType;
        IGirdProfessionalRepository girdProfessionalRepository;
        IMapper mapper;
        ILogger<PagingFormTypeInfoHandler> logger;

        public PagingFormTypeInfoHandler(IFormTypeRepository formType, IGirdProfessionalRepository girdProfessionalRepository, IMapper mapper, ILogger<PagingFormTypeInfoHandler> logger)
        {

            this.formType = formType;
            this.girdProfessionalRepository = girdProfessionalRepository;
            this.mapper = mapper;
            this.logger = logger;
        }

        public async Task<ApiResult<ApiPaging<PagingFormTypeInfoRespDto>>> Handle(PagingFormTypeInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                //带分页的表单数据列表
                var formtypeList = await formType.GetPageListAsync(request.PageIndex, request.PageSize, x => !x.IsDel
                && (string.IsNullOrEmpty(request.TypeNo) || x.TypeNo.Contains(request.TypeNo))
                && (request.ProfessionalId == null || x.ProfessionalId == request.ProfessionalId));
/*
                //dto实例
                List<PagingFormTypeInfoRespDto> dto = mapper.Map<List<PagingFormTypeInfoRespDto>>(formtypeList);
                //查找对应的行业
                var girdList =await girdProfessionalRepository.GetAll().ToListAsync();
                //循环添加数据
                foreach ( var item in dto)
                {
                    item.ProfessionalName = girdList.Find(x => x.ProfessionalId == item.ProfessionalId).ProfessionalName;
                }*/

                //转换类型
                var result = mapper.Map<ApiPaging<PagingFormTypeInfoRespDto>>(formtypeList);

                return ApiResult<ApiPaging<PagingFormTypeInfoRespDto>>.Success(result, StateCodeEnum.Ok);
            }
            catch (Exception ex)
            {
                logger.LogError("表单分页列表出错" + ex.Message);
                throw;
            }
        }
    }
}
